<?php

namespace app\admin\controller\work;

use app\common\controller\Backend;
use app\common\model\cost\Cost;
use app\common\model\Equipment;
use app\common\model\Workflow;
use app\common\model\Hospital;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 维保工单管理
 *
 * @icon fa fa-circle-o
 */
class Protect extends Backend
{

    /**
     * Protect模型对象
     * @var \app\common\model\work\Protect
     */
    protected $model = null;
    protected $selectpageFields='id,name';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\work\Protect;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("billingDataList", $this->model->getBillingDataList());
        $this->view->assign("typeDataList", $this->model->getTypeDataList());
        $this->view->assign("collectDataList", $this->model->getCollectDataList());
        $this->view->assign("openDataList", $this->model->getOpenDataList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $user=$this->auth->getUserInfo();
            $hospital = Hospital::field("id")->where(["status" => 1])
                ->where('FIND_IN_SET("' . $user["id"] . '", admin_ids)')->find();
            $where1='1=1';
            if($hospital) $where1=" protect.hospital_id = ".$hospital["id"];
            $list = $this->model
                    ->with(['hospital','user','equipment', 'engineer'=>function($query){
                        $query->withField('id,nickname');
                    },
                        'sale'=>function($query){
                            $query->withField('id,nickname');
                        }])
                    ->where($where)
                    ->where($where1)
                    ->where(["type_data"=>1])
                    ->order($sort, $order)
                    ->paginate($limit);
            $ids=$this->model
                ->field("GROUP_CONCAT(protect.id) ids")
                ->alias("protect")
                ->join("user user","protect.user_id=user.id","left")
                ->join("hospital hospital","protect.hospital_id=hospital.id","left")
                ->join("equipment equipment","protect.equipment_id=equipment.id","left")
                ->join("user engineer","protect.engineer_id=engineer.id","left")
                ->join("user sale","protect.sale_id=sale.id","left")
                ->where($where)
                ->where($where1)
                ->where(["protect.type_data" => '1'])->find();
            $ids=$ids["ids"];
            $final_price_sum=0;//成交价
            $receivable_sum=0;//应收
            $profit_sum=0;//利润
            foreach ($list as $k=>$row) {
                $row->visible(['id','product','profit','device','open_data','contacts','mobile','status','billing_data','createtime','final_price','workID','collect_data']);
                $row->visible(['hospital']);
				$row->getRelation('hospital')->visible(['name']);
                $row->visible(['equipment']);
                $row->getRelation('equipment')->visible(['id','name','marking','serial','enclosure','software_version']);
				$row->visible(['user']);
				$row->getRelation('user')->visible(['id','nickname']);
                $xshk=\app\admin\model\work\Xshk::where(["warranty_id"=>$row["id"]])->sum("money");
                $row->xshk=$xshk;
                $receivable=0;
                if(empty($row->user_id)) $row->user->nickname="平台";
                if(!empty($row["final_price"]) && $row["final_price"]>0){
                    $cost=Cost::where(["warranty_id"=>$row["id"],"status"=>'1'])->sum("money");
                    $row->profit=$row["final_price"]-$cost;
                    $receivable=$row["final_price"]-$xshk;
                }else{
                    $row->profit=0;
                }
                $row->receivable=$receivable;
                /*$final_price_sum+=$row["final_price"];
                $receivable_sum+=$receivable;*/
                $profit_sum+=$row->profit;
                /*2022-11-22 李娜 新增 start*/
                $row->visible(['engineer']);
                $row->getRelation('engineer')->visible(['id','nickname']);
                $row->visible(['sale']);
                $row->getRelation('sale')->visible(['id','nickname']);
                /*2022-11-22 李娜 新增 end*/
            }
            $xshk=0;
            $final_price_sum=$this->model->where(["type_data"=>'1'])->whereIn("id",$ids)->where($where1)->sum("final_price");//成交价
            $xshk=\app\admin\model\work\Xshk::with("warranty")->whereIn("warranty_id",$ids)->where($where1)->where(["type_data"=>"1"])->sum("money");//回款记录
            $cost=Cost::with("warranty")->where(["type_data"=>"1"])->whereIn("warranty_id",$ids)->where($where1)->where(["cost.status"=>'1'])->sum("money");//成本
            $receivable_sum=$final_price_sum-$xshk;//利润  成交价-回款记录
            $profit_sum=$final_price_sum-$cost;//应收账款  成交价-成本
            $result = array("total" => $list->total(), "rows" => $list->items(), "final_price_sum"=>floor($final_price_sum *100)/100,
                "receivable_sum"=>floor($receivable_sum *100)/100,
                "profit_sum"=>floor($profit_sum *100)/100,);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                $time=time();
                $equipment=Equipment::get($params["equipment_id"]);
                $servicetime=json_decode($equipment["next_json"],true);
                $data=[];
                $data_status=false;
                foreach ($servicetime as  $row => &$v) {
                    $next=strtotime($v['time'].' 00:00:00');
                    $now=strtotime(date('Y-m-d',time()).' 00:00:00');
                    if($next>$now) $data_status=true;
                }
                if(!$data_status){
                    $this->error("该设备没有设置待保养时间");
                }
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    unset($params["servicetime"]);
                    $params["type_data"]=1;
                    $params["status"]=1;
                    $params["createtime"]=$time;
                    //$params["number"]=count($servicetime);
                    if($params["department_id"]) unset($params["department_id"]);
                    $params["surplus_num"]=$params["maintain_num"];
                    $result = $this->model->allowField(true)->insertGetId($params);
                    $id = $result;
                    $i=0;
                    foreach ($servicetime as  $row => &$v) {
                        $i++;
                        $next=strtotime($v['time'].' 00:00:00');
                        $now=strtotime(date('Y-m-d',time()).' 00:00:00');
                        if($next>$now){
                            $data[] = array('warranty_id' => $result,'status'=>'3','type_data'=>'1','number'=>$i,  'servicetime' => $next,"createtime"=>$time);
                        }
                    }
                    if($data){
                        \app\common\model\work\Service::insertAll($data);//记录下次维修时间
                    }
                    $number=count($data);
                    Workflow::create([
                        "warranty_id"=>$id,
                        "hospital_id"=>$params["hospital_id"],
                        "type_data"=>7,
                        "title"=>'工单已创建',
                        "content"=>'维保工单已创建，请等待工程师上门保养。',
                        "createtime"=>$time,
                    ]);//记录工作流
                    $result=\app\common\model\work\Warranty::where(["id"=>$id])->update(["workID"=>"12".date("y",time()).$id,
                        "number"=>$number
                        ]);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                \app\common\model\work\Service::whereIn('warranty_id',explode(",",$ids))->delete();//记录下次维修时间
                Workflow::whereIn('warranty_id',explode(",",$ids))->delete();
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
